package com.yunchang.springboot.quatrz.scheduler;

import com.yunchang.springboot.mapper.base.BaseReportInfoMapper;
import com.yunchang.springboot.mapper.log.LogReportRecordMapper;
import com.yunchang.springboot.models.base.BaseReportInfo;
import com.yunchang.springboot.models.log.LogReportRecord;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

/**
 * @author czw
 * @date 2020/7/30 0030  14:26
 * @description:
 */
@Component
@EnableScheduling
@Slf4j
public class ReportScheduler {

    @Value("${timedJobPath}")
    private String jobPath;

    /**
     * scheduler工厂bean，用于创建scheduler
     */
    private SchedulerFactoryBean schedulerFactoryBean;

    @Autowired
    public void setSchedulerFactoryBean(SchedulerFactoryBean schedulerFactoryBean) {
        this.schedulerFactoryBean = schedulerFactoryBean;
    }

    /**
     * 基础报告信息
     */
    private BaseReportInfoMapper baseReportInfoMapper;

    @Autowired
    public void setBaseReportInfoMapper(BaseReportInfoMapper baseReportInfoMapper) {
        this.baseReportInfoMapper = baseReportInfoMapper;
    }

    /**
     * 获取报告过程日志记录
     */
    private LogReportRecordMapper logReportRecordMapper;

    @Autowired
    public void setLogReportRecordMapper(LogReportRecordMapper logReportRecordMapper){
        this.logReportRecordMapper = logReportRecordMapper;
    }

//    @Scheduled(cron = "01 56 14 13 08 ?")
    public void schedulerTest() throws SchedulerException {
        log.info("开始mws拉取数据测试，时间：" + LocalDateTime.now().toString());
        List<BaseReportInfo> baseReportInfoList = baseReportInfoMapper.selectAllData();
        for (BaseReportInfo baseReportInfo : baseReportInfoList) {
            Scheduler scheduler = schedulerFactoryBean.getScheduler();
            scheduler.start();
            String name = baseReportInfo.getJobName();
//            String groupName = baseReportInfo.getJobGroup();
            String cronExpression = baseReportInfo.getTimedCronExpression();
            String reportName = baseReportInfo.getChineseReportName();
            Class<? extends Job> jobClass = null;
            try {
                jobClass = (Class<? extends Job>) Class.forName(jobPath + baseReportInfo.getTimedJobClass());
            } catch (ClassNotFoundException e) {
                // 获取报告日志记录对象
                LogReportRecord logReportRecord = new LogReportRecord();
                logReportRecord.setReportInfoId(baseReportInfo.getId());
                logReportRecord.setRemarks("job类不存在!");
                logReportRecord.setAddTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
                logReportRecord.setModTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
                logReportRecordMapper.insertSelective(logReportRecord);
            }
            // 创建对应的job类
            JobDetail job = newJob(jobClass)
                    .withIdentity(name,"groupName")
                    .usingJobData("reportName",reportName)
                    .usingJobData("reportType",baseReportInfo.getReportType())
                    .usingJobData("timeScope",baseReportInfo.getReportTimeScope())
                    .usingJobData("getReportArea",baseReportInfo.getGetReportArea())
                    .usingJobData("reportInfoId",baseReportInfo.getId())
                    .build();
            // 根据cron表达式创建触发器
            Trigger trigger = newTrigger()
                    .withIdentity(name, "groupName")
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression).withMisfireHandlingInstructionFireAndProceed())
                    .build();
            // 将job和触发器作为参数启动scheduler
            scheduler.scheduleJob(job, trigger);
        }
    }
}
